/*
    SlideScript - minimalistic top-down scripting language.
    (C) Copyright 2014-2022 Chris Dorman - some rights reserved (GPLv2)

    View README file supplied with this software for more details
*/

#include "inc/deps.h"
#include "inc/inset.h"
#include "inc/lexer.h"
#include "inc/vars.h"
#include "inc/util.h"

BQ s_bqf [MAX_BQ_FUNCTIONS];

void s_inset(int index, char *function)
{
    s_bqf[index].function = qmalloc(QM_BQ, (strlen(function) + 1));
    strcpy(s_bqf[index].function, function);
}

int get_bq_count()
{
    int yy;
    for(yy = 0; yy < MAX_BQ_FUNCTIONS; yy++)
    {
        if(s_bqf[yy].function != NULL)
        {
            continue;
        }
        else
        {
            return yy;
        }
    }
    return 0;
}

char *parse_bq(char *string)
{
    int str_char, var_len;
    char *varbuffer, *finished;

    /* String pointers */
    char *input_pointer;
    char *output_pointer;
    char *variable_pointer;

    varbuffer = qmalloc(QM_BQ, strlen(string) + 1);
    finished = qmalloc(QM_BQ, (strlen(string) + 1));

    *finished = NULLBYTE;

    for (input_pointer = string, output_pointer = finished;
         (str_char = *input_pointer) != NULLBYTE;
         input_pointer++)
    {
        if (str_char != TOKEN_BQ)
            { *output_pointer++ = str_char; *output_pointer = NULLBYTE; continue; }

        variable_pointer = varbuffer;
        do { *variable_pointer++ = (str_char = *++input_pointer); }
            while ((str_char != NULLBYTE) && (str_char != TOKEN_BQ));

        str_char = *input_pointer;
        if ((str_char != NULLBYTE) && (str_char != TOKEN_BQ))
            syn_error("ss:error:backquote buffer out of sync");
        str_char = variable_pointer [-1];
        if ((str_char != NULLBYTE) && (str_char != TOKEN_BQ))
            syn_error("ss:error:backquote out of sync");

        variable_pointer[-1] = NULLBYTE;

        if(*varbuffer == NULLBYTE)
            syn_error("ss:error:backquote syntax error!");

        // Add newline so other function processing doesn't miss end quotes
        strcat (varbuffer, "\n");

        variable_pointer = process_line(varbuffer);
        //tar_free_pool();
        if(variable_pointer == NULL)
            syn_error("ss:error:backquoted function must return string!");

        var_len = strlen(variable_pointer);

        int moo = output_pointer - finished;
        finished = qrealloc(finished, (strlen(finished) + var_len + 1));
        output_pointer = moo + finished;

        strcat (finished, variable_pointer);
        output_pointer += var_len;
        if(*input_pointer == NULLBYTE) break;
    }

    *output_pointer = NULLBYTE;
    return finished;
}

